package com.dykj.fireFighting.web.base.app;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.system.entity.SysUser;
import com.dykj.fireFighting.api.base.system.service.ISysLogService;
import com.dykj.fireFighting.api.base.system.service.ISysUserService;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.constant.CommonConstant;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.dykj.fireFighting.web.base.shiro.jwt.JwtTokenUtil;
import com.dykj.fireFighting.web.base.system.dto.SysLoginDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Api(value = "app登录退出接口", tags = {"app登录退出接口"})
@RestController
@RequestMapping(value = "/app")
public class AppLoginController {

    @DubboReference
    private ISysUserService userService;

    @DubboReference
    private IEnterpriseService enterpriseService;

    @DubboReference
    private ISysLogService sysLogService;


    @Resource
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 全局缓存名称前缀，默认为应用名
     */
    @Value("${spring.application.name}")
    private String cacheKeyPrefix;

    /**
     * 登录
     */
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/sys/login")
    public CommonResult login(@RequestBody SysLoginDto loginDto, HttpServletRequest request) {

        String username = (loginDto.getUsername());
        String password = (loginDto.getPassword());
        String clientId = request.getHeader(CommonConstant.SIGN_CLIENT_ID_KEY);


        if (StringUtils.isBlank(username)) {
            return CommonResult.failed("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return CommonResult.failed("密码不能为空");
        }

        SysUser sysUser = userService.selectByLoginName(username);

        if (ObjectUtils.isEmpty(sysUser)) {
            return CommonResult.failed("账号不存在");
        }
        if (!sysUser.getPassword().equals(ShiroUtil.md5(password, username + sysUser.getSalt()))) {
            return CommonResult.failed("密码不正确");
        }
        if (sysUser.getStatus() == 1) {
            return CommonResult.failed("账号被禁用");
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        //TODO:当企业不存在或者企业被禁用不允许登录
        if (sysUser.getId() != CommonConstant.SUPER_ADMIN) {
            Enterprise sysEnterprise = enterpriseService.getById(sysUser.getEnterpriseId());
            if (null == sysEnterprise) {
                return CommonResult.failed("企业不存在，该账户不允许登录");
            } else if (sysEnterprise.getStatus() == 1) {
                return CommonResult.failed("企业被禁用，该账户不允许登录");
            } else if (!sysEnterprise.getEnterpriseType().toString().equals(clientId)) {
                return CommonResult.failed("该账户不允许登录");
            }
            loginUserVo.setEnterpriseName(sysEnterprise.getEnterpriseName());
        }

        //TODO: 生成token

        BeanUtils.copyProperties(sysUser, loginUserVo);
        String token = jwtTokenUtil.generateToken(loginUserVo);
        ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<>();
        concurrentMap.put("token", token);
        concurrentMap.put("userInfo",loginUserVo);
        log.info(" 用户名:  " + loginUserVo.getName() + ",登录成功！ ");
        sysLogService.addLog(loginUserVo.getLoginName(), "用户名: " + loginUserVo.getName() + ",登录成功！", 1, null);
        return CommonResult.success(concurrentMap);
    }


    /**
     * 加密
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "加密", notes = "加密")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "data", value = "待加密字符串", required = false, dataType = "String"),
    })
    @GetMapping("/sys/encrypt")
    public String encrypt(String data) {
        /** AES加解密 */
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "1234567812345678".getBytes(), "1234567812345678".getBytes());
        // 解密
        String s = aes.encryptBase64(data);
        return s;
    }

    /**
     * 解密
     *
     * @param encrypt
     * @return
     */
    private String decrypt(String encrypt) {
        /** AES加解密 */
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "1234567812345678".getBytes(), "1234567812345678".getBytes());
        // 解密
        String s = aes.decryptStr(encrypt).replace("\"", "");
        return s;
    }
}
